package com.kepler.social.web.comp;

import com.kepler.social.common.constants.Enums;
import com.kepler.social.domain.user.security.UserSecurityRepository;
import com.kepler.social.service.vo.SysUserVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class LoginValidateAuthenticationProvider extends BaseAuthenticationProvider implements AuthenticationProvider {
    @Resource
    private UserSecurityRepository userSecurityRepository;
    //解密用的
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取输入的用户名
        String username = authentication.getName();
        SysUserVo sysUser = new SysUserVo();
        try{
            sysUser.setId(Long.parseLong(username));
            sysUser.setLoginMethod(Enums.LoginMethodEnum.EMAIL.code);
            sysUser.setPassword(userSecurityRepository.findValidUserPassword(Long.parseLong(username)));
        }catch (IllegalArgumentException e){
            throw new UsernameNotFoundException(e.getMessage());
        }catch (Exception e){
            log.error("findUserPassword name {} err {}", username, e, e);
            throw new UsernameNotFoundException("系统错误，请联系管理员");
        }
        UserDetails user = getUserDetails(sysUser);
        //获取输入的明文
        String rawPassword = (String) authentication.getCredentials();
        //验证密码
        if (!passwordEncoder.matches(rawPassword, user.getPassword())) {
            throw new BadCredentialsException("输入密码错误!");
        }
        return new UsernamePasswordAuthenticationToken(user, rawPassword, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //确保authentication能转成该类
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
